const cookie = require('cookie');
const cookieParser = require('cookie-parser');
const socket = require('socket.io');
const adapter = require('socket.io-redis');

module.exports = function (server, config, redis) {
    let sid = config.sid || 'connect.sid', secret = config.secret;
    let io = socket(server);
    io.adapter(adapter(redis.getSocketAdapter()));
    io.on('connection', function (client) {
        client.join('broadcast');

        let cookieString = client.request.headers.cookie;
        if (!cookieString)
            return;
        let cookies = cookie.parse(cookieString);
        if (!cookies[sid])
            return;

        let sessionId = "sess:" + cookieParser.signedCookie(cookies[sid], secret);
        redis.globalClient.get(sessionId, function (err, reply) {
            if (err) {
                console.error('\n', error.stack || error.message);
            }
            if (reply) {
                let user_id = JSON.parse(reply).user_id;
                if (user_id) {
                    client.join_room_name = 'user_' + user_id;
                    client.join(client.join_room_name);
                    console.log('######## WebSocket Connection: ', client.id, client.join_room_name);
                }
            }
        });
        client.on('disconnect', function () {
            console.log('######## WebSocket Disconnect: ', client.id, client.join_room_name);
        });
    });

    return {
        sendTask: function (user_id, task) {
            io.to('user_' + user_id).emit('task', task.dataValues || task);
        },
        sendNotification: function (user_id, notification) {
            io.to('user_' + user_id).emit('notification', notification.dataValues || notification);
        },
        broadcast: function (broadcast) {
            io.to('broadcast').emit('broadcast', broadcast);
        }
    };
};